<template>
  <div class="app-container">
    <page-header
      title="概述统计"
      desc="商城统计最新情报及相关设置"
    />
    <el-card shadow="never">
      <div
        slot="header"
        class="d-flex align-items-center justify-content-between"
      >
        <h5 class="m-0">
          <span>统计报告</span>
          <small
            v-if="dateRangeText"
            class="ml-2 text-muted"
          >{{ dateRangeText }}</small>
        </h5>
        <el-radio-group
          v-model="activeDateLabel"
          size="small"
          @change="onChange"
        >
          <el-radio-button
            v-for="(date,index) in datePickerItems"
            :key="index"
            :label="date.name"
            :class="{'custom-datepicker':date.name==='custom'}"
          >
            <span>{{ date.label }}</span>
            <el-date-picker
              v-if="date.custom"
              ref="customPicker"
              v-model="timeRanges"
              size="small"
              type="daterange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              @focus="onPickerFocus"
            />
          </el-radio-button>
        </el-radio-group>
      </div>
      <em-cell-group
        layout="grid"
        grid-column="5"
        gutter="10px"
      >
        <em-cell
          v-for="(item,index) in basics"
          :key="index"
          :title="item.title"
          :label="item.desc"
          center
        >
          <h3 class="m-0 text-success">
            <em-currency
              v-if="item.format==='currency'"
              v-model="item.value"
              symbol=""
            />
            <span v-else>{{ item.value }}</span>
          </h3>
        </em-cell>
      </em-cell-group>

      <el-alert
        type="tips"
        class="mt-3"
        show-icon
        title="统计数据存在10分钟的缓存时间"
      />

      <line-marker
        :data="charts"
        :x-labels="chartXLabels"
      />
    </el-card>
    <div class="grid grid-cols-2">
      <el-card
        shadow="never"
        class="crud"
      >
        <div
          slot="header"
          class="d-flex align-items-center justify-content-between"
        >
          <h5 class="m-0">
            <span>{{ activeTabPrefix }}商品销售TOP30</span>
          </h5>
        </div>
        <el-table
          v-if="topSpus.length>0"
          :data="topSpus"
          style="width: 100%"
          size="small"
        >
          <el-table-column
            type="index"
            label="排名"
          />
          <el-table-column
            prop="name"
            label="商品名称"
          />
          <el-table-column
            prop="sales"
            label="销量"
            sortable
            align="right"
          />
          <el-table-column
            prop="amount"
            label="成交额"
            sortable
            align="right"
          />
        </el-table>
        <el-empty
          v-else
          description="暂无数据"
        />
      </el-card>

      <el-card
        shadow="never"
        class="crud"
      >
        <div
          slot="header"
          class="d-flex align-items-center justify-content-between"
        >
          <h5 class="m-0">
            <span>{{ activeTabPrefix }}店铺销售TOP30</span>
          </h5>
        </div>
        <el-table
          v-if="topStores.length>0"
          :data="topStores"
          style="width: 100%"
          size="small"
        >
          <el-table-column
            type="index"
            label="排名"
          />
          <el-table-column
            prop="store.name"
            label="店铺名称"
          />
          <el-table-column
            sortable
            prop="amount"
            label="销售金额"
            align="right"
          >
            <template slot-scope="scope">
              <em-currency :value="scope.row.amount" />
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="counts"
            label="订单量"
            align="right"
          />
        </el-table>
        <el-empty
          v-else
          description="暂无数据"
        />
      </el-card>
    </div>
  </div>
</template>

<script>
import PageHeader from '@/components/PageHeader'
import LineMarker from '@/components/Charts/LineMarker'
// import ChartLineSmooth from '@/components/Charts/LineSmooth'
// import MixChart from '@/components/Charts/MixChart'
export default {
  components: {
    PageHeader,
    LineMarker
    // ChartLineSmooth,
    // MixChart
  },
  data() {
    var moment = this.$moment
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = moment(end)
                .subtract(3, 'months')
                .toDate()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const end = new Date()
              const start = moment(end)
                .subtract(6, 'months')
                .toDate()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date()
              const start = moment(end)
                .subtract(1, 'years')
                .toDate()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '今年',
            onClick(picker) {
              const end = new Date()
              const start = moment(end)
                .startOf('year')
                .toDate()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '去年',
            onClick(picker) {
              const start = moment()
                .subtract(1, 'years')
                .startOf('year')
                .toDate()
              const end = moment(start)
                .endOf('year')
                .toDate()
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      timeRanges: [],
      stats: [
        {
          title: '下单金额',
          desc: '有效订单的总金额(元)',
          value: 71443,
          format: 'currency',
          name: 'amount'
        },
        {
          title: '下单会员数',
          desc: '有效订单的下单会员总数',
          value: 222,
          name: 'orderUsers'
        },
        {
          title: '下单量',
          desc: '有效订单的总数量',
          value: 302,
          name: 'counts'
        },

        {
          title: '下单商品数',
          desc: '有效订单包含的商品总数量',
          value: 379,
          name: 'orderGoodsNumbers'
        },

        {
          title: '平均价格',
          desc: '有效订单包含商品的平均单价（元）',
          value: 204.44,
          format: 'currency',
          name: 'orderGoodsAverage'
        },

        {
          title: '平均客单价',
          desc: '有效订单的平均每单的金额（元）',
          value: 236.57,
          format: 'currency',
          name: 'orderAmountAverage'
        },
        {
          title: '新增店铺数量',
          desc: '期间内新增店铺的数量',
          value: 22,
          name: 'newStores'
        },
        {
          title: '新增SKU数量',
          desc: '期间内新增商品SKU总数',
          value: 0,
          name: 'newSkus'
        },
        {
          title: 'SPU数量',
          desc: '平台所有有效商品的数量',
          value: 13109,
          name: 'spus'
        },
        {
          title: 'SKU数量',
          desc: '平台所有有效商品规格的数量',
          value: 13109,
          name: 'skus'
        }
      ],
      charts: [],
      chartXLabels: [],
      basicsData: {},
      topStores: [],
      topSpus: [],
      activeDateLabel: 'today',
      datePickerItems: [
        {
          name: 'today',
          text: '今日',
          label: '今天',
          ago: 0,
          custom: false
        },
        {
          name: '7days',
          text: '7日',
          label: '最近7天',
          ago: 7,
          custom: false
        },
        {
          name: '30days',
          text: '30日',
          label: '最近30天',
          ago: 30,
          custom: false
        },
        {
          name: 'custom',
          text: '',
          label: '自定义时间',
          ago: 0,
          custom: true
        }
      ]
    }
  },
  computed: {
    basics() {
      return this.stats.map(item => {
        return {
          ...item,
          value: this.basicsData[item.name] || 0
        }
      })
    },
    dateRangeText() {
      var text = this.activeTabDateRange.map(item => {
        return this.$moment(item).format('YYYY.MM.DD')
      })
      return text.join(' - ')
    },
    activeTabPrefix() {
      return this.activeTab.text || this.dateRangeText
    },
    activeTab() {
      return this.datePickerItems.find(item => {
        return item.name === this.activeDateLabel
      })
    },
    activeTabDateRange() {
      var activeDateTab = this.activeTab
      if (activeDateTab.custom) {
        return this.timeRanges
      } else {
        var enddate = new Date()
        return [
          this.$moment()
            .subtract(activeDateTab.ago, 'days')
            .startOf('day')
            .toDate(),
          enddate
        ]
      }
    }
  },
  watch: {
    timeRanges(v) {
      if (v) {
        this.onLoad()
      }
    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    onLoad() {
      this.$http.stats
        .default({
          datetime: this.activeTabDateRange || []
        })
        .then(res => {
          const { basics, stores, goods } = res.data
          this.basicsData = basics
          this.topStores = stores
          this.topSpus = goods
          this.onLoadChart()
        })
    },
    onLoadChart() {
      this.$http.stats
        .chart({
          datetime: this.activeTabDateRange || []
        })
        .then(res => {
          const { items, labels } = res.data
          this.charts = items
          this.chartXLabels = labels
        })
    },
    onPickerFocus() {
      this.activeDateLabel = 'custom'
    },
    onChange(label) {
      console.log('label', label)
      if (label === 'custom') {
        this.$nextTick(_ => {
          this.$refs.customPicker.focus()
        })
      } else {
        this.onLoad()
        this.timeRanges = this.activeTabDateRange || []
      }
      // var enddate = new Date()
      // if (label === 'today') {
      //   this.timeRanges = [
      //     this.$moment()
      //       .startOf('day')
      //       .toDate(),
      //     enddate
      //   ]
      // } else if (label === '7days') {
      //   this.timeRanges = [
      //     this.$moment()
      //       .subtract(7, 'days')
      //       .toDate(),
      //     enddate
      //   ]
      // } else if (label === '30days') {
      //   this.timeRanges = [
      //     this.$moment()
      //       .subtract(30, 'days')
      //       .toDate(),
      //     enddate
      //   ]
      // }
      // console.log(this.timeRanges)
    }
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
}
//修改控件自带的css
.custom-datepicker {
  position: relative !important;
  ::v-deep .el-range-editor {
    position: absolute; //绝对定位
    top: 0;
    right: 0;
    opacity: 0; //设置完全透明
    width: 100%;
    height: 100%;
    .el-range-input {
      cursor: pointer;
    }
  }
}
.el-card {
  margin-bottom: 15px;
}
.el-card.crud {
  margin-top: 15px;
  ::v-deep .el-card__body {
    padding: 0;
  }
}
</style>
